import {getDictInfoByName} from '@/api/dict.js'
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
import { log } from 'three'
import {addArchive} from '@/api/experimenterTrack'
import {uploadPdf} from '@/api/exam'
const reportFun = {
	data() {
		return {
			upLoadUrl: `${this.baseURL}/minio/upload/permanent`,
			configInstruction: '',
			configAddress: '',
			minFontSize: 12,
			tableSizeEm: 0.6, //表格字体0.6em
			footerSizeEm: 0.8, //footer字体0.8em
			tableCellPadding: 0.3, //tablePadding:0.3em
			pageMargin:{},
			reportsData:{},
			filePath: '',
			configReportFooter:'0'
		}
	},
	filters: {

	},
	beforeDestroy() {
		clearTimeout(this.imgTimer)
	},
	updated() {
		//console.log("updated");
	},
	watch: {

	},
	computed: {

	},
	created(){
		this.getReportFooter()
	},
	mounted() {
		let userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
		if(userAgent.indexOf("Firefox") > -1) {
			this.minFontSize = 6;
		}
		this.getConfig();
	},
	methods: {
		// 配置是否显示页脚
		getReportFooter () {
			getDictInfoByName({ name: 'reportLogoSite' }).then(res => {
				if (res.code == 1) {
					this.configReportFooter = res.attribute.data.value;
				} else {
					this.configReportFooter = '0'
				}
			}).catch(error => {
				this.$Message.error(error)
			})
		},
		//获取尾部地址及描述信息
		getConfig() {
			return new Promise((resolve, reject) => {
				getDictInfoByName({
					name: 'configInstruction'
				}).then(data => {
					if(data.code == 1) {
						this.configInstruction = data.attribute.data.value;
					} else {
						this.configAddress = '';
					}
				}).catch(error => {
					this.configAddress = '';
				})
				getDictInfoByName({
					name: 'configAddress'
				}).then(data => {
					if(data.code == 1) {
						this.configAddress = data.attribute.data.value;
					} else {
						this.configAddress = '';
					}
				}).catch(error => {
					this.configAddress = '';
				})
			})
		},
		//查询是否显示logo
		//计算页面margin
		setPageMargin() {
			let winWidth = (document.body.clientWidth || document.documentElement.clientWidth);
			let pageWidth = 42.5 * this.fontSize;
			let pageNum = Math.floor(winWidth / pageWidth);
			let remainWidth = winWidth - pageWidth * pageNum;
			let margin = Math.floor((remainWidth / (pageNum * 2)) - 2) + 'px';
			this.pageMargin = {
				marginLeft: margin,
				marginRight: margin
			}
		},
		//表格页渲染相关
		//表格数据分页
		getTablePageData(tableCol, tableData) {
			//初始表格列宽
			this.setTableColWidth(tableCol);
			//处理数据，页数和每页表格数据
			return this.dealTableData(tableData,tableCol);
		},
		getRemarkPageData() {
			this.remarkListPageNumArr = []
			let imgs = [...document.querySelectorAll('.remark-group img')]
			if (imgs.length) { // 内容中存在图片，需要判断图片是否全部加载完
				this.imgIsLoaded(imgs)
			} else { // 内容中没有图片，开始根据每个P标签的高端设置每一页的内容，高度超出则另起一页
				this.assemblyRemarkPage()
			}
		},
		// 判断图片是否都已经加载完毕
		imgIsLoaded(imgs) {
			clearTimeout(this.imgTimer)
			// 图片没有加载完，两秒后继续轮训判断是否加载完毕
			if (imgs.some(item => !item.complete)) {
				this.imgTimer = setTimeout(() => {
					this.imgIsLoaded(imgs)
				}, 2000)
				return
			}
			// 图片全部加载完毕，开始根据每个P标签的高端设置每一页的内容，高度超出则另起一页
			this.assemblyRemarkPage()

		},
		assemblyRemarkPage() {
			let pageContentHeight = (document.querySelector('.pageContent') && document.querySelector('.pageContent').clientHeight) || 0
			if (pageContentHeight === 0) { // 没有高度可用，暂时不做任何处理，后期有问题再修改
				return
			}
			let contentList = document.querySelectorAll('.remark-group p')
			let ret = []
			let htmlText = ''
			let availableHeight = pageContentHeight
			for (let index = 0, length = contentList.length; index < length; index++) {
				let pHeight = contentList[index].clientHeight
				let className = contentList[index].className
				if (availableHeight > pHeight) { // 可用高度足够，将当前P标签添加到当前页的内容中
					availableHeight -= pHeight
					htmlText = this.combiningStrings(htmlText, contentList[index].innerHTML, className)
					
				} else { // 可用高度不够，重置可用高度，保存当前页数据，并重新拼接下一页数据
					availableHeight = pageContentHeight
					availableHeight -= pHeight
					ret.push(htmlText)
					htmlText = ''
					htmlText = this.combiningStrings(htmlText, contentList[index].innerHTML, className)
				}
			}
			// 便利完整，保存最后拼接的一页数据
			ret.push(htmlText)
			this.remarkListPageNumArr = ret
		},
		combiningStrings(original, str, className) {
			if (className) {
				if (className === 'user-name') { // 用户名需要加粗
					return original += `<p class="${className}">${str}:</p>`
				} else {
					return original += `<p class="${className}"></p>`
				}
			} else {
				return original += `<p>${str}</p>`
			}
		},
		setTableColWidth(tableCol) {
			//把每一列的宽度计算出来
//			this.reportCol = tableCol;
			let size = this.getSize();
			let tableWidth = this.getTableWidth(); //去掉外padding+内padding
			tableCol.filter(col => col.width).forEach(col => {
				col.width = (col.title.length + 1) * size + this.getTableCellPadding();
				tableWidth -= col.width;
			})
			tableCol.filter(col => !col.width).forEach(col => {
				col.width = tableWidth * col.per;
			})
		},
		dealTableData(tableData,tableCol) {
			let size = Math.ceil(this.fontSize < this.minFontSize ? this.minFontSize : this.fontSize);
			let tableHeight = this.getContentHeight() - this.getTableHeaderHeight(tableCol) - 33; //减去标题
			let totalHeight = 0;
			let pageData = [];
			let page = 1;
			let rankListPageNumArr = [];
			tableData.forEach(item => {
				let height = this.getRowHeight(item,tableCol) + 1
				totalHeight += height;
//				console.log(height, totalHeight, tableHeight)
				if(totalHeight <= tableHeight) {
					if(rankListPageNumArr.find(rank => rank.page == page)) {
						rankListPageNumArr[page - 1].data.push(item);
						rankListPageNumArr[page - 1].totalHeight = totalHeight;
					} else {
						rankListPageNumArr.push({
							tableHeight: tableHeight,
							totalHeight: totalHeight,
							page: page,
							data: [item],
						});
					}
				} else {
					pageData = [];
					totalHeight = height + 1;
					page++;
					rankListPageNumArr.push({
						tableHeight: tableHeight,
						totalHeight: totalHeight,
						page: page,
						data: [item],
					});
				}
			})
			return rankListPageNumArr;
		},
		getTableWidth() {
			return this.fontSize * (42.5 - 2 * 2 - 2); //去掉外padding2em+内padding1em
		},
		getContentWidth() {
			return this.fontSize * (42.5 - 2 * 2); //去掉外padding2em
		},
		getSize(sizePer = this.tableSizeEm) {
			let size = this.fontSize * sizePer < this.minFontSize ? this.minFontSize : this.fontSize * sizePer;
			return size;
		},
		getTableCellPadding() {
			let size = this.getSize();
			return size * this.tableCellPadding * 2;
		},
		getRowHeight(rowData,tableCol) {
			let heightArr = tableCol.map(col => {
				let text = rowData[col.key];
				return this.getHeightWithText(text, this.tableSizeEm, col.width - this.getTableCellPadding(), rowData, col.key);
			});
			let height = Math.max(...heightArr);
			return height;
		},
		getTableHeaderHeight(tableCol) {
			let obj = {};
			tableCol.forEach(col => {
				obj[col['key']] = col['title']
			})
//			console.log('头高度', this.getRowHeight(obj) * 1.5);
			return this.getRowHeight(obj,tableCol) * 1.5
		},
		getFooterHeight () {
			if(!this.configInstruction || this.configInstruction.length == 0) {
				return 40
			}
			let tableWidth = this.getContentWidth()// * 0.96 - 136;
			let configHeight = this.getHeightWithText(this.configInstruction, this.footerSizeEm, tableWidth);
			let locationHeight = this.fontSize * 1.5 + 14; //21 + 14
			let marginHeight = this.fontSize * this.footerSizeEm * 2;
			return configHeight + locationHeight + marginHeight;
		},
		getContentHeight() {
			//(height:60.143em - padding(2*2) - (内部padding 1*2em) -(头部:27 + 2em))
//			console.log('footer高度', this.getFooterHeight());
			return 54 * this.fontSize - (27 + 2 * this.fontSize) - 20 - (this.configReportFooter == '1' ?  12.8 : this.getFooterHeight());
		},
		getHeightWithText(txt, sizePer, width, rowData, key) {
			if(!txt && txt !== 0) {
				return 0
			}
			let text = txt + '' || '';
			let text_length = 0;
			let maxRow = 1;
			let size = this.getSize(sizePer);
			let reg = /[\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5]/;
			let enReg = /^[A-Za-z]+$/;
			let enCaReg = /^[A-Z]+$/; //大写字母
			let znReg = /[\u4e00-\u9fa5]/; //中文
			let numReg = /^[0-9]*$/; //数字
			let lineTextNum = Math.floor(width / size); //个数
			let num = 0;
			let lineObj = [];
			let row = 1;
			for(let i = 0; i < text.length; i++) {
				if (text.charAt(i) == '「') { // 这个中文符号，报错 , 直接替换成英文
					text = text.replace(/「/g, '[')
				} else if (text.charAt(i) == '」') {
					text = text.replace(/」/g, ']')
				}
				if(znReg.test(text.charAt(i)) && !reg.test(text.charAt(i))) { //中文
					//					console.log('中文'+text.charAt(i))
					num += 1; //中文算一个
					if(num <= lineTextNum) {
						if(lineObj[row]) {
							lineObj[row].push(text.charAt(i))
						} else {
							lineObj[row] = [text.charAt(i)]
						}
					} else {
						num = 1;
						row++;
						lineObj[row] = [text.charAt(i)]
					}
				} else if(enReg.test(text.charAt(i)) || numReg.test(text.charAt(i))) { //英文，数字
					//					console.log('英文',text.charAt(i),enReg.test(text.charAt(i)),numReg.test(text.charAt(i)));
					let per;
					if(enCaReg.test(text.charAt(i))) {
						per = 0.76; //大写字母按照0.68个算
					} else {
						per = 0.5 //小写字母和数字按照0.5个算
					}
					num += per;
					if(num <= lineTextNum) {
						if(lineObj[row]) {
							lineObj[row].push(text.charAt(i))
						} else {
							lineObj[row] = [text.charAt(i)]
						}
					} else {
						num = per;
						row++;
						lineObj[row] = [text.charAt(i)]
					}
				} else { //字符
					//					console.log('字符',text.charAt(i));
					if(reg.test(text.charAt(i))) { //中文字符
						num++;
						if(num >= lineTextNum) {
							num = 2;
							lineObj[row].pop();
							row++;
							lineObj[row] = [text.charAt(i - 1), text.charAt(i)];
							//								i++;
						} else {
							lineObj[row].push(text.charAt(i));
						}
					} else {
						//console.log('其他',text.charAt(i));
						num += 0.5;
						if(num <= lineTextNum) {
							if(lineObj[row]) {
								lineObj[row].push(text.charAt(i))
							} else {
								lineObj[row] = [text.charAt(i)]
							}
						} else {
							num = 0.5;
							row++;
							lineObj[row] = [text.charAt(i)]
						}
					}
				}
			}
			//console.log(text, lineObj, lineTextNum);
			if(rowData && key) {
				let str = '';
				let arr = Object.values(lineObj);
				rowData[key] = arr.map((val, index) => {
					if(val) {
						return val.join('')
					} else {
						return ''
					}
				}).join('\n')
			}
			//console.log('-----'+text,row,lineTextNum,size,size * row * 1.5);
			if(row - Math.floor(row) > 0.03) {
				row = Math.ceil(row)
			} else {
				row = Math.floor(row)
			}
			//console.log(text,text_length,size,width,(text_length * size) / width,size,row);
			return size * row * 1.5
		},
					// 返回值：arg1加上arg2的精确结果
			accAdd(arg1, arg2) {
				let r1, r2, m;
				try {
					r1 = arg1.toString().split(".")[1].length
				} catch(e) {
					r1 = 0
				};
				try {
					r2 = arg2.toString().split(".")[1].length
				} catch(e) {
					r2 = 0
				};
				m = Math.pow(10, Math.max(r1, r2));
				return(arg1 * m + arg2 * m) / m
			},

			// 返回值：arg1减去arg2的精确结果
			accSub(arg1, arg2) {
				let r1, r2, m, n;
				try {
					r1 = arg1.toString().split(".")[1].length
				} catch(e) {
					r1 = 0
				};
				try {
					r2 = arg2.toString().split(".")[1].length
				} catch(e) {
					r2 = 0
				};
				m = Math.pow(10, Math.max(r1, r2));
				// 动态控制精度长度
				n = (r1 >= r2) ? r1 : r2;
				return((arg1 * m - arg2 * m) / m).toFixed(n);
			},
			downloadReports() {
				this.disDownloadReport = true;
				document.documentElement.scrollLeft = 0;
				document.documentElement.scrollTop = 0;
				let docs = document.querySelectorAll('.reportPage:not(.hidden)')
				let pdf = new jsPDF('p', 'pt', 'a4');
				this.pageDataArr = [];
				let proArr = Array.from(docs).map((doc, index) => {
					return this.htmlToCanvas(doc, index);
				})
				Promise.all(proArr).then(data => {
					for(let i = 0; i < this.pageDataArr.length; i++) {
						let contentWidth = data[0].width;
						let contentHeight = data[0].height;
						//a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
						let imgWidth = 595;
						let imgHeight = 595 / contentWidth * contentHeight;
						pdf.addImage(this.pageDataArr[i], 'JPEG', 0, 0, imgWidth, imgHeight);
						if(i < docs.length - 1) {
							pdf.addPage();
						}
					}
					setTimeout(() => {
						pdf.save((this.reportInfo.name || this.reportInfo.examinationName) + "报告.pdf");
						this.disDownloadReport = false;
					}, 2000)
				})
			},
			htmlToCanvas(doc, index) {
				return new Promise((resolve, reject) => {
					const box = window.getComputedStyle(doc);
					// 获取DOM 节点计算后宽高
					const width = box.width.replace('px', '')
					const height = box.height.replace('px', '')
						// 获取像素比
					//console.log(window.devicePixelRatio);
					const scaleBy = window.devicePixelRatio > 1 ? window.devicePixelRatio : 1;
					html2canvas(doc, {
						scale: window.devicePixelRatio * 2,
						width,
						height,
						scrollX: 0,
						scrollY: 0
					}).then((canvas) => {
						let pageData = canvas.toDataURL('image/jpeg', 1.0);
						//		  console.log(index,pageData);
						this.pageDataArr[index] = pageData;
						resolve(canvas);
					}).catch(error => {

					})
				})
			},
			saveArchive(data){
				document.documentElement.scrollLeft = 0;
				document.documentElement.scrollTop = 0;
				let docs = document.querySelectorAll('.reportPage:not(.hidden)')
				let pdf = new jsPDF('p', 'pt', 'a4');
				this.pageDataArr = [];
				let proArr = Array.from(docs).map((doc, index) => {
					return this.htmlToCanvas(doc, index);
				})
				this.$Message.info('正在归档请稍后')
				this.reportsData=data
				Promise.all(proArr).then(data => {
					for(let i = 0; i < this.pageDataArr.length; i++) {
						let contentWidth = data[0].width;
						let contentHeight = data[0].height;
						//a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
						let imgWidth = 595;
						let imgHeight = 595 / contentWidth * contentHeight;
						pdf.addImage(this.pageDataArr[i], 'JPEG', 0, 0, imgWidth, imgHeight);
						if(i < docs.length - 1) {
							pdf.addPage();
						}
					}
					setTimeout(() => {
						var dataurl = pdf.output('blob');
						this.saveArchive2(dataurl)
					}, 8000)
				})
			},
			saveArchive2(pdf){
				let pdfBase64Str = pdf;
				let file = new File(
					[pdfBase64Str],
					this.reportsData.name + ".pdf",
					{
						type: "application/pdf",
					}
				);
				console.log(pdfBase64Str,'pdfBase64StrpdfBase64Str');
				let formData = new window.FormData()
				formData.append('file',file);
				console.log(formData.get('file'))
				console.log(formData)
				uploadPdf(formData).then(res=>{
					console.log(res,11111111111);
					if(res.code==1){
						this.filePath=res.data
						this.saveRepots()
					}else{
						this.$Message.warning(res.message)
					}
				})
				// $.ajax({
                //     type: 'post',
                //     url: `${this.upLoadUrl}?visibility=company&type=docs&bucket=docs`, //上传文件的请求路径
                //     data: formData,
                //     dataType: "json",
                //     contentType: 'multipart/form-data',
                //     processData: !1,
                //     success:function(res){
                        
                //     },
                //     fail:function(e){
                       
                //     }
                // });
				// this.axios({
				// 			method:'post',
                //             url:`${this.upLoadUrl}?visibility=company&type=docs&bucket=docs`,
                //             // transformRequest: [function(data) {
				// 			// 	return data
				// 			// }],
				// 			data:formData,
                //             headers: {'Content-Type': 'multipart/form-data'},
				// 			onUploadProgress: progressEvent => {
                //             }
                //         }).then(res=>{
				// 			if(res.data.code==1){
				// 			} else{
				// 				this.$Message.warning(res.data.message)
				// 			}
				// 		}).catch(err=>{
                //                 console.log(err)
                //         })
			},
			saveRepots(){
				this.reportsData.filePath=this.filePath
				addArchive(this.reportsData).then(res=>{
					console.log(res);
					if(res.code==1){
						this.$Message.success('归档成功')
					}else{
						this.$Message.warning(res.message)
					}
				})
			},
	}
}
export default reportFun